package com.house365.core.util;

import java.util.List;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RecentTaskInfo;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Handler;
import android.text.InputFilter;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.MarginLayoutParams;
import android.view.Window;
import android.widget.EditText;
import android.widget.Gallery;
import android.widget.TextView;
import android.widget.Toast;

import com.house365.core.R;
import com.house365.core.action.ActionTag;
import com.house365.core.inter.ConfirmDialogListener;
import com.house365.core.inter.DialogOnPositiveListener;

public class ActivityUtil {

	public static void showToastView(Context context, String msg) {
		View toastRoot = LayoutInflater.from(context).inflate(R.layout.toast,
				null);
		TextView message = (TextView) toastRoot.findViewById(R.id.message);
		message.setGravity(Gravity.CENTER);
		message.setText(msg);
		Toast toastStart = new Toast(context);
		toastStart.setGravity(Gravity.CENTER, 0, 10);
		toastStart.setDuration(Toast.LENGTH_LONG);
		toastStart.setView(toastRoot);
		toastStart.show();
	}

	public static void showToastResView(Context context, int resource) {
		View toastRoot = LayoutInflater.from(context).inflate(resource, null);
		Toast toastStart = new Toast(context);
		toastStart.setGravity(Gravity.CENTER, 0, 10);
		toastStart.setDuration(Toast.LENGTH_SHORT);
		toastStart.setView(toastRoot);
		toastStart.show();
	}

	public static AlertDialog showDialogAlert(Context context, int resource) {
		final AlertDialog dlg = new AlertDialog.Builder(context).create();
		dlg.show();
		Window window = dlg.getWindow();
		window.setContentView(resource);
		return dlg;
	}

	public static void showToastView(Context context, int resId) {
		View toastRoot = LayoutInflater.from(context).inflate(R.layout.toast,
				null);
		TextView message = (TextView) toastRoot.findViewById(R.id.message);
		message.setText(resId);
		Toast toastStart = new Toast(context);
		toastStart.setGravity(Gravity.CENTER, 0, 10);
		toastStart.setDuration(Toast.LENGTH_LONG);
		toastStart.setView(toastRoot);
		toastStart.show();
	}

	public static void showToast(Context context, CharSequence text) {
		Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
	}

	public static void showToast(Context context, int resId) {
		Toast.makeText(context, resId, Toast.LENGTH_SHORT).show();
	}

	@Deprecated
	public static void showDialog(Context context, String msgStr) {
		new AlertDialog.Builder(context)
				.setMessage(msgStr)
				.setPositiveButton(R.string.dialog_button_ok,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.dismiss();
							}
						}).show();
	}

	@Deprecated
	public static void showDialog(Context context, int msgResId) {
		new AlertDialog.Builder(context)
				.setMessage(msgResId)
				.setPositiveButton(R.string.dialog_button_ok,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.dismiss();
							}
						}).show();
	}

	@Deprecated
	public static void showConfrimDialog(Context context, String msgStr,
			final DialogOnPositiveListener onPositiveListener) {
		new AlertDialog.Builder(context)
				.setMessage(msgStr)
				.setNegativeButton(R.string.dialog_button_cancel,
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.dismiss();
							}
						})
				.setPositiveButton(R.string.dialog_button_ok,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								if (onPositiveListener != null) {
									onPositiveListener.onPositive(dialog);
								}
								dialog.dismiss();
							}
						}).show();
	}

	@Deprecated
	public static void showConfrimDialog(Context context, int msgStrId,
			final DialogOnPositiveListener onPositiveListener) {
		new AlertDialog.Builder(context)
				.setMessage(msgStrId)
				.setNegativeButton(R.string.dialog_button_cancel,
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.dismiss();
							}
						})
				.setPositiveButton(R.string.dialog_button_ok,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								if (onPositiveListener != null) {
									onPositiveListener.onPositive(dialog);
								}
								dialog.dismiss();
							}
						}).show();
	}

	@Deprecated
	public static void showConfrimDialog(Context context, int NegativeButtonId,
			int PositiveButtonId, int titleStrId, int msgStrId,
			final ConfirmDialogListener onConfirmDialogListener) {
		new AlertDialog.Builder(context)
				.setCancelable(false)
				.setTitle(titleStrId)
				.setMessage(msgStrId)
				.setNegativeButton(NegativeButtonId,
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.dismiss();
								if (onConfirmDialogListener != null) {
									onConfirmDialogListener.onNegative(dialog);
								}
							}
						})
				.setPositiveButton(PositiveButtonId,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								if (onConfirmDialogListener != null) {
									onConfirmDialogListener.onPositive(dialog);
								}
								dialog.dismiss();
							}
						}).show();
	}

	// @Deprecated
	public static void exitDialog(final Context context, int appid) {
		new AlertDialog.Builder(context)
				.setTitle(appid)
				.setMessage(R.string.confirm_exit_info)
				.setPositiveButton(R.string.dialog_button_exit,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.dismiss();
								Intent intent = new Intent(
										ActionTag.INTENT_ACTION_LOGGED_OUT);
								context.sendBroadcast(intent);
								((Activity) context).getApplication()
										.onTerminate();
							}

						})
				.setNegativeButton(R.string.dialog_button_cancel,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.dismiss();
							}

						}).create().show();
	}

	/***
	 * ����������������
	 * 
	 * @param context
	 * @param titleId
	 * @param key
	 * @param content
	 * @param maxSize
	 * @param inputType
	 * @param positiveClick
	 * 
	 *            demo:inputTextBox("�ǳ�:",regUser.nickName,7,InputType.
	 *            TYPE_TEXT_VARIATION_NORMAL);
	 */
	public static void inputTextBox(final Context context, int titleId,
			final String key, String content, int maxSize, int inputType,
			final InputTextBoxOnClickListener positiveClick) {
		AlertDialog.Builder alert = new AlertDialog.Builder(context);
		alert.setTitle(titleId);
		// alert.setIcon(android.R.drawable.ic_dialog_info);
		final EditText input = new EditText(context);
		InputFilter[] filters = new InputFilter[1];
		filters[0] = new InputFilter.LengthFilter(maxSize);
		input.setFilters(filters);
		input.setInputType(inputType);
		input.setText(content);
		input.setLines(1);
		alert.setView(input);
		alert.setPositiveButton(R.string.dialog_button_ok,
				new OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						positiveClick.onClick(dialog, which, input);
						dialog.dismiss();
					}
				});
		alert.setNegativeButton(R.string.dialog_button_cancel,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						dialog.dismiss();
					}
				});
		alert.show();

	}

	/***
	 * ����������������
	 * 
	 * @param context
	 * @param titleId
	 * @param key
	 * @param content
	 * @param maxSize
	 *            ���Ƴ���
	 * @param inputType
	 * @param line
	 *            ����
	 * @param positiveClick
	 */
	public static void inputTextBox(Context context, int titleId,
			final String key, String content, int maxSize, int inputType,
			int line, final InputTextBoxOnClickListener positiveClick) {
		AlertDialog.Builder alert = new AlertDialog.Builder(context);
		alert.setTitle(titleId);
		final EditText input = new EditText(context);
		InputFilter[] filters = new InputFilter[1];
		filters[0] = new InputFilter.LengthFilter(maxSize);
		input.setFilters(filters);
		input.setInputType(inputType);
		input.setText(content);
		input.setLines(line);
		input.setGravity(Gravity.TOP);
		alert.setView(input);
		alert.setPositiveButton(R.string.dialog_button_ok,
				new OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						positiveClick.onClick(dialog, which, input);
					}
				});
		alert.setNegativeButton(R.string.dialog_button_cancel,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						dialog.dismiss();
					}
				});
		alert.show();

	}

	public interface InputTextBoxOnClickListener {
		public void onClick(DialogInterface dialog, int which, EditText view);

	}

	public static void showItemLongChooseDialog(Context context,
			CharSequence[] items,
			final ItemLonngDialogOnChooseListener onChooseListener) {
		new AlertDialog.Builder(context).setItems(items,
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						switch (which) {
						case 0:
							onChooseListener.chooseFirst(dialog, which);
							break;
						}
						dialog.dismiss();
					}
				}).show();
	}

	public static void showSingleChooseDialog(Context context,
			CharSequence[] items,
			final ItemDialogOnChooseListener onChooseListener) {
		new AlertDialog.Builder(context).setItems(items,
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						onChooseListener.onChoose(dialog, which);
						dialog.dismiss();
					}
				}).show();
	}

	public static void showSingleChooseDialog(Context context, int titleId,
			CharSequence[] items,
			final ItemDialogOnChooseListener onChooseListener) {
		showSingleChooseDialog(context,
				context.getResources().getString(titleId), items,
				onChooseListener);
	}

	public static void showSingleChooseDialog(Context context,
			CharSequence title, CharSequence[] items,
			final ItemDialogOnChooseListener onChooseListener) {
		new AlertDialog.Builder(context).setTitle(title)
				.setItems(items, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						onChooseListener.onChoose(dialog, which);
						dialog.dismiss();
					}
				}).show();
	}

	public interface ItemLonngDialogOnChooseListener {
		public void chooseFirst(DialogInterface dialog, int which);
	}

	public interface ItemDialogOnChooseListener {
		public void onChoose(DialogInterface dialog, int which);
	}

	public static void showPhotoChooseDialog(Context context,
			final PhotoDialogOnChooseListener onChooseListener) {
		new AlertDialog.Builder(context).setItems(R.array.uploadway,
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						switch (which) {
						case 0:
							// ���
							onChooseListener.chooseAlbum(dialog);
							break;
						case 1:
							// ����
							onChooseListener.choosePhoto(dialog);
							break;
						}
						dialog.dismiss();
					}
				}).show();
	}

	public interface PhotoDialogOnChooseListener {
		public void chooseAlbum(DialogInterface dialog);

		public void choosePhoto(DialogInterface dialog);
	}

	public static void alignGalleryToLeft(Context context, Gallery gallery,
			int itemWidth) {
		DisplayMetrics metric = new DisplayMetrics();
		((Activity) context).getWindowManager().getDefaultDisplay()
				.getMetrics(metric);
		int galleryWidth = metric.widthPixels;
		// int itemWidth =
		// context.getResources().getDimensionPixelSize(R.dimen.length80);
		int offset;
		if (galleryWidth <= itemWidth) {
			offset = galleryWidth / 2 - itemWidth / 2 - 5;
		} else {
			offset = galleryWidth - itemWidth - 2 * 5;
		}
		// offset = 0;
		MarginLayoutParams mlp = (MarginLayoutParams) gallery.getLayoutParams();
		mlp.setMargins(-offset, mlp.topMargin, mlp.rightMargin,
				mlp.bottomMargin);
	}

	public static void toDial(final Context context, String telstr,
			String delimiter) {
		if (!TextUtils.isEmpty(telstr)) {
			//
			// // final String[] tels =
			// // shop_detail.getData().getS_tel().split("\\s");
			final String[] tels = telstr.split(delimiter);
			if (tels != null && tels.length > 1) {
				final Builder builder = new AlertDialog.Builder(
						((Activity) context));
				builder.setTitle(R.string.dial_tel);
				builder.setSingleChoiceItems(tels, 0,
						new DialogInterface.OnClickListener() {

							public void onClick(DialogInterface dialog,
									int which) {
								String tel = tels[which];
								dialog.dismiss();
								try {
									((Activity) context)
											.startActivity(IntentUtil
													.getDialIntent(tel));
								} catch (Exception e) {
									e.printStackTrace();
								}

							}

						});
				builder.create().show();
			} else if (tels != null && tels.length == 1) {
				try {
					((Activity) context).startActivity(IntentUtil
							.getDialIntent(tels[0]));
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

		}
	}

	public static String getTopActivity(Context context) {
		ActivityManager manager = (ActivityManager) context
				.getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningTaskInfo> runningTaskInfos = manager.getRunningTasks(1);

		if (runningTaskInfos != null) {
			return (runningTaskInfos.get(0).topActivity).getClassName();
		} else {
			return null;
		}
	}

	public static String getBaseActivity(Context context) {
		ActivityManager manager = (ActivityManager) context
				.getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningTaskInfo> runningTaskInfos = manager.getRunningTasks(1);

		if (runningTaskInfos != null) {
			return (runningTaskInfos.get(0).baseActivity).getClassName();
		} else {
			return null;
		}
	}

	public static boolean isTopActivity(Activity context, String activityName) {
        String s = getTopActivity(context);
        if (s == null) {
            return false;
        }
        return activityName.equals(s);
    }
	
	public static boolean isTopActivity(Activity context) {
		String s = getTopActivity(context);
		if (s == null) {
			return false;
		}
		String s1 = context.getClass().getName();
		return s1.equals(s);
	}

	public static boolean isAppOnForeground(Context context,
			String baseActivtyName) {
		String s = getBaseActivity(context);
		if (s == null) {
			return false;
		}
		return baseActivtyName.equals(s);
	}

	public static boolean isServiceRunning(Context mContext, String className) {
		boolean isRunning = false;
		ActivityManager activityManager = (ActivityManager) mContext
				.getSystemService(Context.ACTIVITY_SERVICE);
		List<ActivityManager.RunningServiceInfo> serviceList = activityManager
				.getRunningServices(Integer.MAX_VALUE);
		if (serviceList == null || (serviceList.size() == 0)) {
			return false;
		}
		for (int i = 0; i < serviceList.size(); i++) {
			if (serviceList.get(i).service.getClassName().equals(className)) {
				isRunning = true;
				break;
			}
		}
		return isRunning;
	}
}
